var dblRoomLayer = {
    initLayer:function(){
        
        //this.ui = new cc.Node()
        cc.BuilderReader.registerController("dblRoom", {})
        this._initCallBack()

        var node  = cc.BuilderReader.load("ccb/dblRoom.ccbi", this);
        this.animationManager = node.animationManager
        this.ccbNode = node

        this.countdownSeconds.setVisible(false)
        this.resultNode.setVisible(false)

        this.hasInit = true

        var env = this
        var listener = cc.EventListener.create({
            event: cc.EventListener.TOUCH_ONE_BY_ONE,
            swallowTouches: true,
            onTouchBegan: function (touch, event) {
                if(!env.ccbNode.isVisible()) 
                    return false

                var target = event.getCurrentTarget()
                var locationInNode = target.convertToNodeSpace(touch.getLocation())
                var s = target.getContentSize();
                var rect = cc.rect(0, 0, s.width, s.height)
                if (cc.rectContainsPoint(rect, locationInNode)) {
                    return true
                }
                return false
            },
            onTouchMoved: function (touch, event) {
                var target = event.getCurrentTarget()
                var delta = touch.getDelta()
                // target.x += delta.x
                // target.y += delta.y
            },
            onTouchEnded: function (touch, event) {
                var target = event.getCurrentTarget()
                env.rulesSpr.setVisible(false)
                env.resultNode.setVisible(false)
            }
        })
        cc.eventManager.addListener(listener, this.ccbNode)

    },
    showRoom:function()
    {
        this.refreshRoom()
        this.ccbNode.setVisible(true)
    },
    hideRoom:function()
    {   
        this.currRoundCards.removeAllChildren()
        this.selfDealNode.setVisible(false)
        this.oppoDealNode.setVisible(false)

        this.resultNode.setVisible(false)
        this.countdownSeconds.setVisible(false)
        this.ccbNode.setVisible(false)
    },
    showGameResult:function(resultData) //计算每个玩家的得分 按得分判断输赢
    {

        for(var i=0;i<3;i++)
        {   
            var resultItem = this['resultItem' + (i+1)]
            var r = resultData[i]
            if (r)
            {
                resultItem.setVisible(true)
                for(var j in r)
                {   
                    var ttf = this['result'+(i+1)+'_'+(parseInt(j)+1)]  
                    ttf.setString(r[j])
                }
            }
            else
            {
                resultItem.setVisible(false)
            }
        }
        this.resultNode.setVisible(true)
    },
    dealCards:function()
    {
        this.selfDealNode.setVisible(true)
        this.oppoDealNode.setVisible(true) 

        if(ROOMDATA._currentRound == 1)
        {
            var aniName = "dealFirst"+ROOMDATA.deskNum+"Player";
            this.animationManager.runAnimationsForSequenceNamedTweenDuration(aniName, 0)
        }
        else
        {
            var aniName = "dealunFirst"+ROOMDATA.deskNum+"Player";
            this.animationManager.runAnimationsForSequenceNamedTweenDuration(aniName, 0)
        }
    },
    refreshCountdown:function()
    {
         //倒计时
        if (ROOMDATA.countdownSeconds <= 0)
            this.countdownSeconds.setVisible(false)
        else
        {
            this.countdownSeconds.setVisible(true)
            this.countdownSeconds.setString(ROOMDATA.countdownSeconds)
        }
    },
    refreshRoom:function()
    {
        if(ROOMDATA.deskNum == 2)
        {
             this.deskNode1.setVisible(true)
             this.deskNode2.setVisible(false)
             this.deskNode3.setVisible(true)
             this.deskNode1.setPosition(cc.p(0, cc.director.getWinSize().height*0.25))
             this.deskNode3.setPosition(cc.p(cc.director.getWinSize().width*0.64, cc.director.getWinSize().height*0.25))
        }
        else if(ROOMDATA.deskNum == 3) 
        {    
             this.deskNode1.setVisible(true)
             this.deskNode2.setVisible(true)
             this.deskNode3.setVisible(true)
             this.deskNode1.setPosition(cc.p(0, cc.director.getWinSize().height*0.5))
             this.deskNode2.setPosition(cc.p(0, 0))
             this.deskNode3.setPosition(cc.p(cc.director.getWinSize().width*0.64, cc.director.getWinSize().height*0.25))
        }
 
        this.roomInfo.setString('房间ID:' + ROOMDATA.id + '\n' + '底注:' + ROOMDATA.bottomBet)
    

        this.currRoundCards.removeAllChildren()
        for(var i=1;i<4;i++)
        {
            this._refreshDesk(i)
            this._refreshCards(i)
        }   

    },
    _refreshDesk:function(deskNodeIdx) //根据每桌的数据刷新界面
    {   
        var deskData = ROOMDATA._desksDataByIdx[deskNodeIdx]
        var deskNode = this['deskNode' + deskNodeIdx]
        var name = this['name' + deskNodeIdx]
        var headIcon = this['headIcon' + deskNodeIdx]
        var wenhao = this['wenhao' + deskNodeIdx]
        if(deskData) 
        {
            headIcon.setVisible(true)
            wenhao.setVisible(false)
            name.setVisible(true)  
            name.setString(deskData.userData.name + '\n' + deskData.userData.gold)  
        }
        else
        {
            headIcon.setVisible(false)
            wenhao.setVisible(true)
            name.setVisible(false)  
        }

    },
    _refreshCards:function(deskNodeIdx) 
    {   
        var deskData = ROOMDATA._desksDataByIdx[deskNodeIdx]
        if(deskData) 
        {   
            //刷新
            if (deskData.userData.id == USERDATA.id)
            {
                this._showNewCards(deskData.newRoundCards)
            }

            this._showCardsOnDesk(deskNodeIdx)

        }
    },
    _initCallBack:function()
    {   

        this.onPopRules = function()
        {
            this.rulesSpr.setVisible(true)
        }

        this.onBack = function()
        {
            cc.log("leaveRoom",USERDATA)
            ioSocket.req('leaveRoom') 
        }

        this.onSureClicked = function()
        {
            var cards = ROOMDATA._desksDataByIdx[3].cards
            var totalNum = cards[0].length + cards[1].length + cards[2].length
            if (totalNum == ROOMDATA._currentRound * 2 + 3)
            {
                ioSocket.req('chooseSure',{cards:cards}) 
            }
            else
            {
                ShowTipsTTF({str:'牌没摆满'})
            }
        }
        this.onDealFirst2Player = function()
        {
            cc.log('1111onDealFirst2Player')
            this.selfDealNode.setVisible(false)
            this.currRoundCards.removeAllChildren()
            for(var i=1;i<4;i++)
            {
                this._refreshCards(i)
            }    
        }
        this.onDealunFirst2Player = function()
        {
            this.selfDealNode.setVisible(false)
            this.currRoundCards.removeAllChildren()
            for(var i=1;i<4;i++)
            {
                this._refreshCards(i)
            }   
        }
        this.onDealFirst3Player = function()
        {
            this.selfDealNode.setVisible(false)
            this.currRoundCards.removeAllChildren()
            for(var i=1;i<4;i++)
            {
                this._refreshCards(i)
            }   
        }
        this.onDealunFirst3Player = function()
        {
            this.selfDealNode.setVisible(false)
            this.currRoundCards.removeAllChildren()
            for(var i=1;i<4;i++)
            {
                this._refreshCards(i)
            }   
        }
    },
    _showNewCards:function(newRoundCards)
    {
        var posY = -250
        var posCenterX = 310
        var lengh = newRoundCards.length
        var intervalX = 300/lengh

        for(var i=0;i<lengh;i++)
        {
            var num = newRoundCards[i]
            var spr = _getCardByNum(num,true)
            spr.x = posCenterX - (lengh-1)/2*intervalX + i*intervalX
            spr.x = spr.x + cc.director.getWinSize().width*0.5
            spr.y = posY + cc.director.getWinSize().height*0.5
            spr.idx = i
            spr.deskNode = this.deskNode3
            spr.originPos = {x:spr.x,y:spr.y}
            this.currRoundCards.addChild(spr,2)
        }
    },
    _showCardsOnDesk:function(deskNodeIdx)
    {   
        var deskData = ROOMDATA._desksDataByIdx[deskNodeIdx]
        var deskNode = this['deskNode' + deskNodeIdx]
        var cards = deskData.cards

        var deskPos = deskNode.getPosition()
        for(var i=0;i<3;i++)
        {
            for(var j=0;j<cards[i].length;j++)
            {
                var num = cards[i][j];
                var spr = _getCardByNum(num);
                var p =  _getPositionByIdx(i,j);
                spr.x = deskPos.x + p.x ;

                spr.y = deskPos.y + p.y;

                this.currRoundCards.addChild(spr);
            }
        }
    },


}

function  _getCardByNum(num,isTouchable)
{
    var picName = num + ".png"

    var spr = new cc.Sprite("#" + picName);
    if(isTouchable)
    {
        cc.eventManager.addListener(_getCardTouchListener(), spr);
    }
    spr.setScale(1);
    return spr
}

///////////////_getCardTouchListener////////////////

function _getCardTouchListener()
{
    //玩家移动扑克时 会改变cards数组 到时传给服务器
    //新一轮的扑克 会加下面的监听
    var _cardTouchListener = cc.EventListener.create({
        event: cc.EventListener.TOUCH_ONE_BY_ONE,
        swallowTouches: true,
        onTouchBegan: function (touch, event) {
            var target = event.getCurrentTarget();
            var locationInNode = target.convertToNodeSpace(touch.getLocation());
            var s = target.getContentSize();
            var rect = cc.rect(0, 0, s.width, s.height);

            if (cc.rectContainsPoint(rect, locationInNode)) {
                cc.log("sprite began... x = " + locationInNode.x + ", y = " + locationInNode.y);
                var x = target.getPositionX() - target.deskNode.getPositionX();
                var y = target.getPositionY() - target.deskNode.getPositionY();
                if (y > 0)
                {
                    var cards =  ROOMDATA._desksDataByIdx[3].cards
                    var idx = _getIdxByPosition(x,y);
                    if(idx.line+1!=cards[idx.row].length)  //桌面上的扑克只有最后一张可以移动
                        return false
                    cards[idx.row].splice(idx.line,1);
                    cc.log("remove1111",idx.row,idx.line);
                }
                target.setLocalZOrder(2);
                return true;
            }
            return false;
        },
        onTouchMoved: function (touch, event) {
            var target = event.getCurrentTarget();
            var delta = touch.getDelta();
            target.x += delta.x;
            target.y += delta.y;
        },
        onTouchEnded: function (touch, event) {
            var target = event.getCurrentTarget();
            var endPosIndex =  _getIndexByTouchPos(touch,target.deskNode);
            var deskPosX = target.deskNode.getPositionX();
            var deskPosY = target.deskNode.getPositionY();
            target.setLocalZOrder(1);
            if(endPosIndex==0)
                target.setPosition(target.originPos.x, target.originPos.y);
            else
            {
                var cards = ROOMDATA._desksDataByIdx[3].cards
                var length = cards[endPosIndex-1].length;
                if( (endPosIndex==3 && length==3) || length==5 ) //移到的目标行 牌满了
                    target.setPosition(target.originPos.x, target.originPos.y);
                else
                {
                    var totalNum = cards[0].length + cards[1].length + cards[2].length;
                    if (totalNum == ROOMDATA._currentRound * 2 + 3) //排满了
                        target.setPosition(target.originPos.x, target.originPos.y);
                    else
                    {
                        var p = _getPositionByIdx(endPosIndex - 1, length);
                        target.setPosition(deskPosX + p.x, deskPosY + p.y);

                        cards[endPosIndex - 1].splice(length, 0, ROOMDATA._desksDataByIdx[3].newRoundCards[target.idx]);
                        //cards[endPosIndex-1][length] = ROOMDATA.getNewRoundCards()[target.idx];
                    }
                }
            }
            cc.log('cards:',ROOMDATA._desksDataByIdx[3].cards)
        },
    })

    return _cardTouchListener
}

function _getPositionByIdx(row,line) // 从0 ，0 开始算
{
    var x = (line+1)*65;
    var y = (row+1)*90 - 30;
    return {x:x,y:y};
}
function _getIdxByPosition(x,y) // 从0 ，0 开始算
{
    var row =  Math.round( (y + 30)/90 -1 );//行数
    var line = Math.round(x/65 -1);

    return {row:row,line:line};
}

function _getIndexByTouchPos(touch,deskNode)// 触摸点 第1、2、3排 和其他地方
{
    var deskPosY = deskNode.getPositionY();
    var deskPosX = deskNode.getPositionX();
    var deskSizeY = deskNode.getContentSize().height;
    var deskSizeX = deskNode.getContentSize().width;
    var touchY = touch.getLocation().y;
    var touchX = touch.getLocation().x;
    if(touchX < cc.director.getWinSize().width - deskSizeX + 30)
        return 0;
    else if(touchY > deskPosY +  deskSizeY)
        return 0;
    else if (touchY > deskPosY +  deskSizeY/3 * 2)
        return 3;
    else if (touchY > deskPosY +  deskSizeY/3)
        return 2;
    else if (touchY > deskPosY)
        return 1;
    else
        return 0;
}

///////////////_getCardTouchListener end////////////////




